# -*- coding: utf-8 -*
from abc import ABC

from app.configs import kj236_pool, global_config
from app.models import db_session
from app.models.model import TrackModel, PositionModel
from app.tools.utils import dt2str, get_item_xy, clear_same_points
from app.views import CommonHandler
from apscheduler.schedulers.tornado import TornadoScheduler


persons, readers = [], []


def get_tracks():
    session = db_session()
    features = session.query(TrackModel).filter(
        TrackModel.meta_id == global_config['mine_code'],
        TrackModel.dxftype == "person"
    ).all()
    session.close()

    keys = [feature.id for feature in features]
    values = [feature.vector() for feature in features]
    clear_same_points(values)
    return dict(zip(keys, values))


def get_positions():
    session = db_session()
    features = session.query(PositionModel).filter(
        PositionModel.meta_id == global_config['mine_code'],
        PositionModel.dxftype == "person"
    ).all()
    session.close()

    keys = [feature.node_id for feature in features]
    values = [feature.vector() for feature in features]
    return dict(zip(keys, values))


def get_readers():
    sql = "SELECT readerid, state, isvalid from m_reader"
    results, items = [], kj236_pool.select(sql)
    for item in items:
        if item[2]:
            results.append({"node_id": str(int(item[0])), "status": item[1]})
    return results


def get_persons():
    rfids, items = {}, kj236_pool.select("SELECT rfnum, readerid, dir, distance from m_rfid")
    for item in items:
        rfids[item[0]] = item

    persons, items = [], kj236_pool.select("SELECT * from view_staff_inmine")
    # persons, items = [], kj236_pool.select(
    #     "with view_staff_inmine as (select * from view_staff_inmine a where 1=1 "
    #     "and coalesce((select d.dicvalue from m_dic d where d.diccode = 'SYS_XTSX_RYHC'),'0') "
    #     "not like '%'''||coalesce(a.worktypeid::text,'')||'''%')select * from view_staff_inmine t"
    # )
    for i in items:
        if i[0] in rfids:
            rfid = rfids[i[0]]
            person = {
                "id": i[0],
                "rfid": i[1],
                "name": i[2],
                "userid": i[3],
                "inminetime": dt2str(i[6]),
                "dep": i[7],
                "duty": i[8],
                "isleader": i[15] if i[15] else False,
                "photo": photos[i[0]] if i[0] in photos else None,
                "classtypeid": i[14],
                "readerid": rfid[1],
                "dir": rfid[2],
                "distance": rfid[3],
            }
            persons.append(person)
    return persons


def get_persons_xys(persons, positions, tracks):
    for person in persons:
        # 1.判断分站是否能存在
        node_id = person['readerid']
        if node_id is None:
            continue

        # 2.获取分站的位置
        node_id = int(node_id)
        if node_id not in positions:
            continue
        postion = positions[int(node_id)]


        # 3.如果分站不在轨迹线上,这里未来要做四方向分站
        if postion['track_id'] not in tracks:
            continue

        # 4.计算人员位置
        direction, d100 = person['dir'], person['distance'] / 100
        xy = get_item_xy(tracks, postion, direction, d100)
        person['x'], person['y'], person['grid'] = xy['x'], xy['y'], xy['grid']
    return persons


def job():
    global persons, readers
    tracks, positions = get_tracks(), get_positions()
    readers, persons = get_readers(), get_persons()
    persons = get_persons_xys(persons, positions, tracks)


def run_cache():
    scheduler = TornadoScheduler()
    scheduler.add_job(job, 'interval', seconds=2, id="person_cache")
    scheduler.start()


# 只有KJ236项目执行此缓存操作
# if 'person' in global_config and global_config['person']['backend']:
#     # 缓存人员照片
#     photos, rs = {}, kj236_pool.select("SELECT * from m_rfid")
#     for r in rs:
#         photos[r[0]] = r[17]
#
#     # 缓存人员位置
#     run_cache()


class PersonHandler(CommonHandler, ABC):
    async def get(self):
        global persons, readers
        await self.response(data={"readers": readers, "persons": persons})
